// page 公用 mixins
const app = getApp();
import { navTo, hideTabbar, reLaunchTo, showTabbar, navBack, tipSuccess, tipError,
    getSetting, getUserInfo as getWxUserInfo, isAuthUserInfo, hidePullDownLoading, copyText, callPhone, showLoading, hideLoading } from '../common/env';
import { PACKAGE_ACTIVITY_PAGE, PACKAGE_MARKET_PAGE, PACKAGE_SIGNIN_PAGE, COMMON_PAGE, TAB_BAR_PAGE, PACKAGE_ORDER_PAGE, PACKAGE_STAR_PAGE, PACKAGE_STORE_PAGE } from '../constants/route';
import { getUserId, getUserInfo, getMangeTargetId, getMangeTargetInfo, setMangeTargetId, setMangeTargetInfo, getMangeTargetType, setOrderOriginInfo, clearOrderOriginInfo } from '../biztools/wex';
import { cartChangeItem, cartAddItem, cartMinusItem, getCartProductList, getCartProductTotal, clearCartData } from '../biztools/cart';
import { getActionMenu } from '../biztools/activity';
import { COS_CONF, DEFAULT_BG_LIST, DEFAULT_SHARE_IMAGE, DEFAULT_SHARE_TITLE, ACTIVITY_TYPE, TARGET_TYPE, SNS_TYPE_MENU } from '../constants/common';
import { ACTIVITY_OWNER_VALUE, ACTIVITY_STATUS_VALUE } from '../constants/activity';
import { ORDER_OWNER_TYPE, ORDER_FILTER_TYPE } from '../constants/order';
import { USER_ACTION_TYPE } from '../constants/user';
import { setUrlParam, getPicFullPath, arr2Obj, getMaxNumber, isEmpty } from '../common/utils';
import { TipDialog } from '../common/tip';
import { getBrandConfig } from '../api/common';
import { statusActivity as statusBrdActivity, updateBrandInfo, getBrandInfo } from '../api/brd';
import { statusActivity as statusStoActivity, updateStoreInfo, getStoreInfo } from '../api/sto';
import { statusActivity as statusSpnActivity } from '../api/spn';
import { updateUserInfo, cancelFollowActivity } from '../api/usr';
import { APPNAME } from '../config';


/**
 * 页面只读数据mixins
 */
export const PageReadonlyDataMixins = {
    data: {
        __readonly__: {
            APPNAME
        }
    }
}

/**
 * 页面分享mixins
 */
export const PageShareMixins = {
    onShareAppMessage(res) {
        if (res.from === 'button') {
            // 来自页面内转发按钮
            let { title='', path='/pages/index/index', image='' } = res.target.dataset.detail || res.target.dataset;
            if (this.data.actionShareInfo && !isEmpty(this.data.actionShareInfo)) {
                const { actionShareInfo } = this.data;
                title = actionShareInfo.title;
                path = actionShareInfo.path;
                image = actionShareInfo.image;
            }
            return {
                title: title || DEFAULT_SHARE_TITLE,
                path: setUrlParam(path, {
                    b: getUserId(),
                }),
                imageUrl: getPicFullPath(image || DEFAULT_SHARE_IMAGE),
            };
        } else {
            return {
                title: DEFAULT_SHARE_TITLE,
                imageUrl: getPicFullPath(DEFAULT_SHARE_IMAGE),
            };
        }
    },
};

/**
 * 页面公用方法
 */
export const PageCommonFuncs = {
    data: {
        isBackIcon: false,
    },
    onShow: function () {
        this.setData({
            isBackIcon: getCurrentPages().length > 1,
        });
    },
    navbarLeftAction: function () {
        const { isBackIcon } = this.data;
        if (isBackIcon) {
            navBack();
        } else {
            this.gotoHomePage();
        }
    },
    gotoHomePage: function () {
        reLaunchTo(TAB_BAR_PAGE.index);
    },
};

/**
 * 生成活动操作项菜单 mixins
 * @param {Boolean} isHaveTabbar 页面是否存在tabbar
 */
const createActivityMixins = (isHaveTabbar = false) =>  {
    return {
        data: {
            showActivityAction: false,
            activityManageActionSheet: {
                show: false,
            },
            activityManageMoreActionMenu: [],
            activityManageInfo: null,
            actionShareInfo: {},
        },
        handleShowActivityManageAction(e) {
            const activityManageInfo = e.detail && e.detail.id ? e.detail : this.data.activityManageInfo;
            const { id, pics, ownerName, name } = activityManageInfo;
            this.setData({
                'activityManageActionSheet.show': true,
                activityManageInfo,
                actionShareInfo: {
                    title: `@${ownerName} ${name}`,
                    path: `${PACKAGE_ACTIVITY_PAGE['detail']}?activityId=${id}`,
                    image: pics[0],
                },
            });
        },
        handleCloseActivityManageAction() {
            this.setData({
                'activityManageActionSheet.show': false,
            });
        },
        handleManageActivityToDetail(e) {
            const { activityId, type, owner, brandId, storeId, spokesmanId, processStatus, canManage } = e.detail;
            if (type === ACTIVITY_TYPE.group_buying) { 
                if (canManage && processStatus === ACTIVITY_STATUS_VALUE.draft) {
                    if (owner === ACTIVITY_OWNER_VALUE.brand) {
                        navTo(PACKAGE_ACTIVITY_PAGE['activityPreview'], {
                            brandId,
                            activityId,
                        });
                    } else if (owner === ACTIVITY_OWNER_VALUE.store) {
                        navTo(PACKAGE_ACTIVITY_PAGE['storeActivityPreview'], {
                            storeId,
                            activityId,
                        });
                    }
                } else {
                    navTo(PACKAGE_ACTIVITY_PAGE['detail'], {
                        activityId,
                        owner,
                    });
                }
            } else if (type === ACTIVITY_TYPE.lottery) {
                if (canManage && processStatus === ACTIVITY_STATUS_VALUE.draft) {
                    navTo(PACKAGE_MARKET_PAGE.lotteryPreview, { brandId, activityId });
                } else {
                    navTo(PACKAGE_MARKET_PAGE.lotteryDetail, {
                        activityId,
                    });
                }
            }
        },
        handleManageActivityMore(e) {
            const activityManageInfo = e.detail && e.detail.id ? e.detail : this.data.activityManageInfo;
            this.handleCloseActivityManageAction();
            isHaveTabbar && hideTabbar();
            this.setData({
                activityManageInfo,
                showActivityAction: true,
                activityManageMoreActionMenu: getActionMenu(activityManageInfo),
            });
        },
        handleManageActivityClose() {
            this.setData({
                showActivityAction: false,
            });
            isHaveTabbar && showTabbar();
        },
        async handleManageActivitySelect(e) {
            const { action } = e.detail;
            const { type, activityId, brandId, storeId, spokesmanId, processStatus, owner } = this.data.activityManageInfo;
            if (action === USER_ACTION_TYPE.shareActivity) {
                console.log('ActivityMixins => 执行了分享');
            } else if (action === USER_ACTION_TYPE.statsConsignmentActivity) {
                // 帮卖管理
                if (owner === ACTIVITY_OWNER_VALUE.brand) {
                    navTo(PACKAGE_ACTIVITY_PAGE['activityStatsConsignment'], { brandId, activityId });
                } else if (owner === ACTIVITY_OWNER_VALUE.store) {
                    navTo(PACKAGE_ACTIVITY_PAGE['storeActivityStatsConsignment'], { storeId, activityId });
                }
            } else if (action === USER_ACTION_TYPE.changeActivity) {
                // 修改活动
                if (type === ACTIVITY_TYPE.group_buying) {
                    if (owner === ACTIVITY_OWNER_VALUE.brand) {
                        navTo(PACKAGE_ACTIVITY_PAGE['activityEdit'], { brandId, activityId });
                    } else if (owner === ACTIVITY_OWNER_VALUE.store) {
                        navTo(PACKAGE_ACTIVITY_PAGE['storeActivityEdit'], { storeId, activityId });
                    }
                } else if (type === ACTIVITY_TYPE.lottery) {
                    navTo(PACKAGE_MARKET_PAGE['lotteryEdit'], { brandId, activityId });
                }
            } else if (action === USER_ACTION_TYPE.copyActivity) {
                // 复制活动
                if (type === ACTIVITY_TYPE.group_buying) {
                    if (owner === ACTIVITY_OWNER_VALUE.brand) {
                        navTo(PACKAGE_ACTIVITY_PAGE['activityEdit'], { brandId, copySourceId: activityId });
                    } else if (owner === ACTIVITY_OWNER_VALUE.store) {
                        navTo(PACKAGE_ACTIVITY_PAGE['storeActivityEdit'], { storeId, copySourceId: activityId });
                    }
                } else if (type === ACTIVITY_TYPE.lottery) {
                    navTo(PACKAGE_MARKET_PAGE['lotteryEdit'], { brandId, copySourceId: activityId });
                }
            } else if (action === USER_ACTION_TYPE.overOrOpenActivity) {
                // 停用、启用活动
                let flag = false;
                if (type === ACTIVITY_TYPE.group_buying) {
                    if (owner === ACTIVITY_OWNER_VALUE.brand) {
                        flag = await statusBrdActivity({ brandId, activityId, processStatus });
                    } else if (owner === ACTIVITY_OWNER_VALUE.store) {
                        flag = await statusStoActivity({ storeId, activityId, processStatus });
                    } else if (owner === ACTIVITY_OWNER_VALUE.spokesman) {
                        flag = await statusSpnActivity({ spokesmanId, activityId, processStatus });
                    }
                } else if (type === ACTIVITY_TYPE.lottery) {
                    flag = await statusBrdActivity({ brandId, activityId, processStatus });
                }
                if (flag) {
                    tipSuccess(processStatus === ACTIVITY_STATUS_VALUE.paused ? '启用成功' : '停用成功');
                    if (this._handleGetDetail) this._handleGetDetail();
                    if (this._handleGetList) this._handleGetList(1);
                    if (this.getListData) {
                        this.setData({
                            pageNo: 1,
                        }, async () => {
                            await this.getListData(true);
                        });
                    }
                    if (this.getActivityListData) {
                        this.setData({
                            pageNo: 1,
                        }, async () => {
                            await this.getActivityListData(true);
                            hidePullDownLoading();
                        });
                    }
                }
            } else if (action === USER_ACTION_TYPE.cancelFollowActivity) {
                // 取消关注活动
                const flag = await cancelFollowActivity(activityId);
                if (flag) {
                    tipSuccess('取消成功');
                    if (this._handleGetDetail) this._handleGetDetail();
                    if (this._handleGetList) this._handleGetList(1);
                    if (this.getListData) {
                        this.setData({
                            pageNo: 1,
                        }, async () => {
                            await this.getListData(true);
                        });
                    }
                    if (this.getActivityListData) {
                        this.setData({
                            pageNo: 1,
                        }, async () => {
                            await this.getActivityListData(true);
                            hidePullDownLoading();
                        });
                    }
                }
            }
        },
        handleManageActivityToOrder() {
            this.handleCloseActivityManageAction();
            const { brandId, activityId, owner } = this.data.activityManageInfo;
            if (owner === ACTIVITY_OWNER_VALUE.brand) {
                navTo(PACKAGE_ORDER_PAGE['brandOrderList'], {
                    brandId,
                    filterType: ORDER_FILTER_TYPE.activity,
                    filterValue: activityId,
                });
            } else if (owner === ACTIVITY_OWNER_VALUE.spokesman) {
                navTo(PACKAGE_ORDER_PAGE['expandOrderList'], {
                    filterType: ORDER_FILTER_TYPE.activity,
                    filterValue: activityId,
                });
            }
        },
        handleManageActivityToStats() {
            this.handleCloseActivityManageAction();
            const { brandId, storeId, spokesmanId, owner, activityId } = this.data.activityManageInfo;
            if (owner === ACTIVITY_OWNER_VALUE.brand) {
                navTo(PACKAGE_ACTIVITY_PAGE['activityStats'], {
                    brandId,
                    activityId,
                });
            } else if (owner === ACTIVITY_OWNER_VALUE.store) {
                navTo(PACKAGE_ACTIVITY_PAGE['storeActivityStats'], {
                    storeId,
                    activityId,
                });
            } else if (owner === ACTIVITY_OWNER_VALUE.spokesman) {
                navTo(PACKAGE_ACTIVITY_PAGE['spokesActivityStats'], {
                    spokesmanId,
                    activityId,
                });
            }
        },
    };
};

// 活动 mixins
export const ActivityMixins = {
    ...PageShareMixins,
    ...createActivityMixins(),
};

// 活动 mixins 含 tabbar
export const ActivityMixinsHaveTabbar = {
    ...PageShareMixins,
    ...createActivityMixins(true),
};

/**
 * 页面菜单公共方法
 */
export const PageActionMenu = {
    data: {
        showPageActionMenu: false,
    },
    showPageAction: function () {
        this.setData({
            showPageActionMenu: true,
        });
    },
    onPageActionClose: function () {
        this.setData({
            showPageActionMenu: false,
        });
    },
};

// 生成图片分享 mixins 结合组件share-image
const createShareImageMixins = (isHaveTabbar = false) =>  {
    return {
        data: {
            shareImageMessageInfo: {},
            shareImageInfo: {},
            showShareImage: false,
        },
        handleShowShareImage(e) {
            isHaveTabbar && hideTabbar();
            const { type = TARGET_TYPE.brand, shareInfo = {} } = e.currentTarget.dataset;
            const userInfo = getUserInfo();
            let shareImageMessageInfo = {};
            if (type === TARGET_TYPE.brand || type === TARGET_TYPE.store || type === TARGET_TYPE.user) {
                let title, path, image;
                if (type === TARGET_TYPE.brand) {
                    shareInfo.homepageBg = shareInfo.homepageBg || DEFAULT_BG_LIST[7];
                    title = `快来涨点人气@${shareInfo.name}`;
                    path = setUrlParam(COMMON_PAGE['shareBrand'], {
                        brandId: shareInfo.brandId,
                        b: getUserId(),
                    });
                    image = shareInfo.homepageBg;
                } else if (type === TARGET_TYPE.store) {
                    shareInfo.homepageBg = shareInfo.homepageBg || DEFAULT_BG_LIST[7];
                    title = `快来涨点人气@${shareInfo.name}`;
                    path = setUrlParam(COMMON_PAGE['shareStore'], {
                        storeId: shareInfo.storeId,
                        b: getUserId(),
                    });
                    image = shareInfo.homepageBg;
                } else if (type === TARGET_TYPE.user) {
                    shareInfo.homepageBg = shareInfo.homepageBg || DEFAULT_BG_LIST[5];
                    title = `快来涨点人气@${shareInfo.nickName}`;
                    path = setUrlParam(COMMON_PAGE['shareUser'], {
                        userId: shareInfo.userId,
                        b: getUserId(),
                        a: shareInfo.userId,
                    });
                    image = shareInfo.homepageBg;
                }
                shareImageMessageInfo = {
                    title,
                    path,
                    image,
                };
            } else if (type === 'activity') {
                shareImageMessageInfo = {
                    title: `@${shareInfo.ownerName} ${shareInfo.name}`,
                    path: setUrlParam(PACKAGE_ACTIVITY_PAGE['detail'], {
                        activityId: shareInfo.activityId,
                        owner: shareInfo.owner,
                        b: getUserId(),
                        a: shareInfo.pubUserId,
                    }),
                    image: shareInfo.pics && shareInfo.pics.length ? shareInfo.pics[0] : DEFAULT_SHARE_IMAGE,
                };
            } else if (type === 'lottery') {
                shareImageMessageInfo = {
                    title: `@${shareInfo.ownerName} ${shareInfo.name}，快来快来~~`,
                    path: setUrlParam(PACKAGE_MARKET_PAGE['lotteryDetail'], {
                        activityId: shareInfo.activityId,
                        b: getUserId(),
                        a: shareInfo.pubUserId,
                    }),
                    image: shareInfo.pics && shareInfo.pics.length ? shareInfo.pics[0] : DEFAULT_SHARE_IMAGE,
                };
            } else if (type === 'signin') {
                shareImageMessageInfo = {
                    title: `@${userInfo.nickName} 快来加入我，一起参与${shareInfo.brandName}签到活动~~`,
                    path: setUrlParam(PACKAGE_SIGNIN_PAGE['detail'], {
                        brandId: shareInfo.brandId,
                        b: getUserId(),
                    }),
                    image: shareInfo.background || DEFAULT_SHARE_IMAGE,
                };
            }
            this.setData({
                shareImageInfo: {
                    type,
                    shareInfo,
                    userInfo,
                },
                shareImageMessageInfo,
                showShareImage: true,
            });
        },
        handleHideShareImage() {
            this.setData({
                showShareImage: false,
            });
            isHaveTabbar && showTabbar();
        },
    }
};

// 生成图片分享 mixins
export const ShareImageMixins = {
    ...PageShareMixins,
    ...createShareImageMixins(),
};

// 生成图片分享 mixins 含 tabbar
export const ShareImageMixinsHaveTabbar = {
    ...PageShareMixins,
    ...createShareImageMixins(true),
};

// 生成代言人分享 mixins 结合组件share-spokesman
const createShareSpokesmanMixins = (isHaveTabbar = false) =>  {
    return {
        data: {
            shareSpokesmanMessageInfo: {},
            shareSpokesmanInfo: {},
            showShareSpokesman: false,
        },
        handleShowShareSpokesman(e) {
            isHaveTabbar && hideTabbar();
            const { shareInfo } = e.currentTarget.dataset;
            shareInfo.homepageBg = shareInfo.homepageBg || DEFAULT_BG_LIST[7];
            const shareSpokesmanMessageInfo = {
                path: setUrlParam(COMMON_PAGE['shareApplySpokesman'], {
                    brandId: shareInfo.brandId,
                    b: getUserId(),
                }),
            };
            this.setData({
                shareSpokesmanMessageInfo,
                shareSpokesmanInfo: shareInfo,
                showShareSpokesman: true,
            });
        },
        handleHideShareSpokesman() {
            this.setData({
                showShareSpokesman: false,
            });
            isHaveTabbar && showTabbar();
        },
        handleChangeSpokesmanMessageInfo(e) {
            const info = e.detail;
            const { shareSpokesmanMessageInfo } = this.data;
            this.setData({
                shareSpokesmanMessageInfo: {
                    ...shareSpokesmanMessageInfo,
                    ...info,
                },
            });
        },
    }
};

// 生成代言人分享 mixins
export const ShareSpokesmanMixins = {
    ...PageShareMixins,
    ...createShareSpokesmanMixins(),
};

// 生成代言人分享 mixins 含 tabbar
export const ShareSpokesmanMixinsHaveTabbar = {
    ...PageShareMixins,
    ...createShareSpokesmanMixins(true),
};

// 生成分销员分享 mixins 结合组件share-distributor
const createShareDistributorMixins = (isHaveTabbar = false) =>  {
    return {
        data: {
            shareDistributorMessageInfo: {},
            shareDistributorInfo: {},
            showShareDistributor: false,
        },
        handleShowShareDistributor(e) {
            isHaveTabbar && hideTabbar();
            const { shareInfo } = e.currentTarget.dataset;
            shareInfo.homepageBg = shareInfo.homepageBg || DEFAULT_BG_LIST[7];
            const shareDistributorMessageInfo = {
                path: setUrlParam(COMMON_PAGE['shareApplyDistributor'], {
                    brandId: shareInfo.brandId,
                    b: getUserId(),
                }),
            };
            this.setData({
                shareDistributorMessageInfo,
                shareDistributorInfo: shareInfo,
                showShareDistributor: true,
            });
        },
        handleHideShareDistributor() {
            this.setData({
                showShareDistributor: false,
            });
            isHaveTabbar && showTabbar();
        },
        handleChangeDistributorMessageInfo(e) {
            const info = e.detail;
            const { shareDistributorMessageInfo } = this.data;
            this.setData({
                shareDistributorMessageInfo: {
                    ...shareDistributorMessageInfo,
                    ...info,
                },
            });
        },
    }
};

// 生成分销员分享 mixins
export const ShareDistributorMixins = {
    ...PageShareMixins,
    ...createShareDistributorMixins(),
};

// 生成分销员分享 mixins 含 tabbar
export const ShareDistributorMixinsHaveTabbar = {
    ...PageShareMixins,
    ...createShareDistributorMixins(true),
};

// 用户设置相关 mixins
export const UserInfoEditMixins = {
    userInfoUpdataAction: async function (params) {
        const flag = await updateUserInfo(params);
        if (flag) {
            if (this.data.userInfo) {
                this.setData({
                    userInfo: getUserInfo(),
                });
            }
            navBack();
        }
        else tipError('更新失败，请重试');
    },
};

export const UserInfoUpdateMixins = {
    onLoad() {
        console.log('UserInfoMixins => 更新当页用户信息');
        this.setData({
            userInfo: getUserInfo(),
        });
    },
    onShow: function () {
        console.log('UserInfoMixins => 更新当页用户信息');
        this.setData({
            userInfo: getUserInfo(),
        });
    },
};

export const UserAuthInfoEditMixins = {
    data: {
        userAuth: false, // 是否已授权获取用户信息
    },
    onShow() {
        getSetting().then(async info => {
            const flag = isAuthUserInfo(info);
            this.setData({
                userAuth: !!flag,
            });
        });
    },
    async userAuthInfoUpdataAction(e) {
        let { userInfo } = e ? e.detail : {};
        if (!userInfo) {
            userInfo = await getWxUserInfo();
        }
        const { avatarUrl: pic, nickName } = userInfo;
        const flag = await updateUserInfo({ pic, nickName });
        if (flag) {
            tipSuccess('更新成功');
            if (this.data.userInfo) {
                this.setData({
                    userInfo: getUserInfo(),
                });
            }
        } else tipError('更新失败，请重试');
    },
};

// 品牌(店铺)管理相关mixins
export const ManageTargetInfoEditMixins = {
    async manageTargetInfoUpdateAction(params) {
        showLoading('保存中...');
        let flag = false;
        const type = getMangeTargetType();
        if (type === TARGET_TYPE.brand) {
            flag = await updateBrandInfo(params)
        } else if (type === TARGET_TYPE.store) {
            flag = await updateStoreInfo(params);
        }
        if (flag) {
            hideLoading();
            navBack();
        }
        else tipError('更新失败，请重试');
    },
};

export const ManageTargetInfoUpdateMixins = {
    data: {
        manageTargetId: '',
        manageTargetType: '',
        manageTargetInfo: {},
    },
    onLoad() {
        console.log('onLoad ManageInfoUpdateMixins => 更新当页管理品牌、门店Id、信息');
        this.setData({
            manageTargetId: getMangeTargetId(),
            manageTargetType: getMangeTargetType(),
            manageTargetInfo: getMangeTargetInfo(),
        });
    },
    onShow() {
        console.log('onShow ManageInfoUpdateMixins => 更新当页管理品牌、门店Id、信息');
        this.setData({
            manageTargetInfo: getMangeTargetInfo(),
        });
    },
};

export const ManageTargetExchangeMixins = {
    data: {
        manageTargetId: '',
        manageTargetType: '',
        manageTargetInfo: {},
    },
    async _handleExchange(type, manageTargetId) {
        if (type !== getMangeTargetType() || (manageTargetId && manageTargetId !== getMangeTargetId())) {
            let manageTargetType = type, manageTargetInfo;
            if (type === TARGET_TYPE.brand) {
                manageTargetInfo = await getBrandInfo({ brandId: manageTargetId });
                manageTargetId = manageTargetInfo.brandId;
            } else if (type === TARGET_TYPE.store) {
                manageTargetInfo = await getStoreInfo({ storeId: manageTargetId });
                manageTargetId = manageTargetInfo.storeId;
            }
            setMangeTargetId(manageTargetType, manageTargetId);
            setMangeTargetInfo(manageTargetInfo);
            this.setData({ manageTargetId });
            this.setData({ manageTargetType });
            this.setData({ manageTargetInfo });
        }
    },
};

// 页面列表数据
export const PageListMixins = {
    data: {
        pageSize: 10,
        pageNo: 1,
        pageTime: new Date().getTime(),
    },
    onLoad: function () {
        const that = this;
        if (!app.globalData.isReadyAuth) {
            const originFunc = app.userIdentifyCallback;
            app.userIdentifyCallback = (...args) => {
                that.onLoad(...args);
                return originFunc && originFunc(...args);
            }
            return;
        } else {
            this.setData({
                pageTime: new Date().getTime(),
            }, async () => {
                await this.getListData();
            });
        }
    },
    onPullDownRefresh: function () {
        this.setData({
            pageNo: 1,
            pageTime: new Date().getTime(),
        }, async () => {
            await this.getListData(true);
            hidePullDownLoading();
        });
    },
    onReachBottom: function () {
        const { pageNo } = this.data;
        this.setData({
            pageNo: pageNo + 1,
            pageSize: 10,
        }, async () => {
            await this.getListData(false);
        });
    },
};

// 活动页面列表数据
export const ActivityListMixins = {
    data: {
        pageSize: 10,
        pageNo: 1,
        pageTime: new Date().getTime(),
        activeIndex: 'all',
    },
    // 切换分类
    onTabChange: function(event) {
        const { name } = event.detail;
        console.log('ActivityListMixins => 切换类型', name);
        this.setData({
            pageNo: 1,
            pageTime: new Date().getTime(),
            activeIndex: name,
        }, async () => {
            await this.getActivityListData(true);
        });
    },
    onPullDownRefresh: function () {
        this.setData({
            pageNo: 1,
            pageTime: new Date().getTime(),
        }, async () => {
            await this.getActivityListData(true);
            hidePullDownLoading();
        });
    },
    onReachBottom: function () {
        const { pageNo } = this.data;
        this.setData({
            pageNo: pageNo + 1,
            pageSize: 10,
        }, async () => {
            await this.getActivityListData(false);
        });
    },
    refreshListData: async function () {
        console.log('ActivityListMixins => 刷新列表');
        this.setData({
            pageNo: 1,
            pageTime: new Date().getTime(),
        }, async () => {
            await this.getActivityListData(true);
        });
    },
};

// 页面列表数据scroll
export const PageScrollListMixins = {
    data: {
        loaded: false,
        keyword: '',
        filter: {},
        pageData: {
            refresh: false,
            ts: Date.now(),
            pageNo: 1,
            total: 0,
            rows: [],
        },
    },
    onShow() {
        const _ = this;
        if (!app.globalData.isReadyAuth) {
            const originFunc = app.userIdentifyCallback;
            app.userIdentifyCallback = (...args) => {
                _.onShow(...args);
                return originFunc && originFunc(...args);
            }
            return;
        } else {
            const { filters = [], filter } = this.data;
            if (filters.length) {
                filter[filters[0].value] = 'desc';
                this.setData({ filter }, () => {
                    this._handleGetList(1);
                })
            } else {
                this._handleGetList(1);
            }
        }
    },
    handlePageRefresh() {
        this.setData({ loaded: false, 'pageData.refresh': true }, () => {
            this._handleGetList(1);
        });
    },
    handlePageLoad() {
        const { pageNo, rows, total } = this.data.pageData;
        if (rows.length && rows.length < total) {
            this.setData({ loaded: false }, () => {
                this._handleGetList(pageNo + 1);
            });
        }
    },
    handleSearchChange(e) {
        this.setData({ keyword: e.detail });
    },
    handleSearch() {
        this._handleGetList(1);
    },
    handleFilter(e) {
        this.setData({ filter: e.detail });
        this._handleGetList(1);
    },
};

// OSS资源
export const PageOssMixins = {
    data: {
        cosConf: COS_CONF,
        defaultBgList: DEFAULT_BG_LIST,
    },
};

/**
 * 订单列表Mixins
 */
export const OrderListMixins = {
    data: {
        pageSize: 10,
        pageNo: 1,
        activeIndex: 'all',
        pageTime: new Date().getTime(),
    },
    // 切换分类
    onTabChange: function(event) {
        const { name } = event.detail;
        console.log('OrderListMixins => 切换类型', name);
        this.setData({
            pageNo: 1,
            pageTime: new Date().getTime(),
            activeIndex: name,
        }, async () => {
            await this.getOrderListData(true);
        });
    },
    onPullDownRefresh: function () {
        console.log('OrderListMixins => 下拉刷新');
        this.setData({
            pageNo: 1,
            pageTime: new Date().getTime(),
        }, async () => {
            await this.getOrderListData(true);
            hidePullDownLoading();
        });
    },
    onReachBottom: function () {
        console.log('OrderListMixins => 上拉加载下一页');
        const { pageNo } = this.data;
        this.setData({
            pageNo: pageNo + 1,
        }, async () => {
            await this.getOrderListData(false);
        });
    },
    refreshListData: async function () {
        console.log('OrderListMixins => 刷新列表');
        this.setData({
            pageNo: 1,
            pageTime: new Date().getTime(),
        }, async () => {
            await this.getOrderListData(true);
        });
    },
};

/**
 * 订单详情Mixins
 */
export const OrderDetailMixins = {
    // 下拉刷新
    onPullDownRefresh: async function () {
        console.log('OrderDetailMixins => 下拉刷新');
        const { serialNumber } = this.data.orderDetail;
        await this.refreshOrderDetail(serialNumber);
        hidePullDownLoading();
    },
    // 联系商家
    contactBrand: function () {
        const { activityOwner, activityTel, parentActivityTel } = this.data.orderDetail;
        if (activityOwner === ORDER_OWNER_TYPE.spokesman) {
            callPhone(parentActivityTel);
        } else {
            callPhone(activityTel);
        }
    },
    // 联系代言人
    contactSpokesman: function () {
        const { activityTel } = this.data.orderDetail;
        callPhone(activityTel);
    },
    // 联系买家
    contactUser: function () {
        const { buyerTel } = this.data.orderDetail;
        callPhone(buyerTel);
    },
};

/**
 * 售后单详情Mixins
 */
export const AfterSaleOrderDetailMixins = {
    // 下拉刷新
    onPullDownRefresh: async function () {
        console.log('AfterSaleOrderDetailMixins => 下拉刷新');
        const { serialNumber } = this.data.afterSaleOrderDetail;
        await this.refreshAfterOrderDetail(serialNumber);
        hidePullDownLoading();
    },
    // 复制退货地址
    copyBackAddress: function () {
        const { returnGoodsAddressInfo={} } = this.data.afterSaleOrderDetail;
        copyText(`${returnGoodsAddressInfo.linkman} ${returnGoodsAddressInfo.tel} ${returnGoodsAddressInfo.address}`);
    },

    // 复制退货单号
    copyBackExpress: function () {
        const { returnGoodsLogisticsInfo={} } = this.data.afterSaleOrderDetail;
        copyText(`${returnGoodsLogisticsInfo.name} ${returnGoodsLogisticsInfo.no}`);
    },
    // 联系商家
    contactBrand: function () {
        const { activityOwner, activityTel, parentActivityTel } = this.data.afterSaleOrderDetail;
        if (activityOwner === ORDER_OWNER_TYPE.spokesman) {
            callPhone(parentActivityTel);
        } else {
            callPhone(activityTel);
        }
    },
    // 联系代言人
    contactSpokesman: function () {
        const { activityTel } = this.data.afterSaleOrderDetail;
        callPhone(activityTel);
    },
    // 联系买家
    contactUser: function () {
        const { buyerTel } = this.data.afterSaleOrderDetail;
        callPhone(buyerTel);
    },
};

/**
 * 下单、购物车相关
 */
export const OriginEnsureToOrderReviewMixins = {
    data: {
        originId: '',
        originInfo: {},
        cartInfo: {
            list: [],
            map: {},
            totalPrice: 0,
            totalAmount: 0,
        },
        targetProduct: {},
        showProductList: false,
        showProductSku: false,
        showProductDetail: false,
        showBindMobile: false,
        needBindMobile: true,
        canModifySku: false,
        shareUserId: '',
    },
    // --- 下单、购物车相关 ---
    // 刷新购物车信息
    handleRefreshCartData: function () {
        const { originId, originInfo } = this.data;
        if (!originInfo || !originId) return;
        const list = getCartProductList(originId);
        const cartInfo = {
            list,
            map: arr2Obj(list, 'productId'),
            ...getCartProductTotal(originId),
        };
        this.setData({ cartInfo });
    },
    // 打开展示商品、购物
    handleShowProductList() {
        this.setData({
            showProductList: true,
        });
    },
    // 打开商品详情
    handleShowProductDetail(e) {
        const { originInfo } = this.data;
        if (originInfo.processStatus && originInfo.processStatus !== ACTIVITY_STATUS_VALUE.processing) return;
        console.log('打开商品详情为：', e.detail);
        this.setData({
            showProductDetail: true,
            targetProduct: e.detail,
        });
    },
    // 打开选择商品(规格)
    handleShowChooseProduct(e) {
        const { cartInfo, originInfo, canModifySku = false } = this.data;
        let productInfo = e.detail;
        if (originInfo.processStatus && originInfo.processStatus !== ACTIVITY_STATUS_VALUE.processing) return;
        console.log('打开商品规格选择为：', productInfo, originInfo);
        if ((!cartInfo.map[productInfo.productId] || canModifySku) && productInfo.productAttributeDefs && productInfo.productAttributeDefs.length) {
            if (canModifySku) {
                this.handleRemoveCartItem(e);
            }
            if (productInfo.count) {
                productInfo.count = 0;
            } else {
                return;
            }
            this.setData({
                showProductSku: true,
                targetProduct: productInfo,
            });
        } else {
            if (!cartInfo.map[productInfo.productId]) {
                productInfo.selectSku = productInfo.skus[0];
            } else {
                cartInfo.map[productInfo.productId].count = productInfo.count;
                productInfo = cartInfo.map[productInfo.productId];
            }
            this.handleEnsureChooseProduct(productInfo);
        }
    },
    // 确认选择规格
    handleEnsureChooseProduct(e) {
        const { originId } = this.data;
        const productInfo = e.detail ? e.detail : e;
        console.log('选择的产品(规格)为：', productInfo);
        // 添加商品到购物车数据
        cartChangeItem(productInfo, originId);
        this.handleRefreshCartData();
    },
    // 去结算页面
    handleEnsureOrderReview(e) {
        let { mobile } = this.data.userInfo;
        if (!mobile && e.detail) {
            mobile = e.detail.mobile;
        }
        const { originId, originInfo, cartInfo, shareUserId, needBindMobile } = this.data;
        if (needBindMobile && !mobile) {
            this.setData({
                showBindMobile: true,
            });
            return;
        }
        if (!cartInfo.list.length || (originInfo.minimumPurchaseAmount && cartInfo.totalPrice < originInfo.minimumPurchaseAmount)) {
            return;
        }
        console.log('去结算页面：', cartInfo);
        // 保存当前活动信息
        showLoading('下单中...');
        setOrderOriginInfo(originId, this.data.originInfo);
        // 跳转到确认页
        navTo(PACKAGE_ORDER_PAGE.orderReview, {
            orderOriginId: originId,
            shareUserId,
        });
        hideLoading();
    },
    // 自动移除购物车(售罄、数量)
    handleAutoRemoveSellOut() {
        const { originId, originInfo } = this.data;
        if (!originInfo || !originId) return;
        const cartProducts = getCartProductList(originId);
        const { activityProductWithAttributeDefAndSkus } = originInfo;
        cartProducts.forEach(productInfo => {
            const { count } = productInfo;
            const { productId, productSpecId } = productInfo.selectSku;
            const product = activityProductWithAttributeDefAndSkus.find(p => p.productId === productId);
            const sku = product ? product.skus.find(s => s.productSpecId === productSpecId) : null;
            if (sku) {
                const maxCount = sku && sku.maximum != -1 ? (sku.maximum - sku.freezeQuantity) : getMaxNumber();
                if (maxCount === 0) {
                    this._handleMinusCartItem(productInfo, count);
                } else if (maxCount < count) {
                    this._handleMinusCartItem(productInfo, count - maxCount);
                }
            }
        });
        this.handleRefreshCartData();
    },
    // 自动加入购物车
    handleAutoAddCart() {
        const { cartInfo, originInfo } = this.data;
        const { activityProductWithAttributeDefAndSkus } = originInfo;
        activityProductWithAttributeDefAndSkus.forEach(p => {
            if (!cartInfo.map[p.productId] && p.productAttributeDefs && p.productAttributeDefs.length) {
            } else {
                p.selectSku = p.skus[0];
                p.count = p.count || p.quantity;
                this.handleEnsureChooseProduct(p);
            }
        });
    },
    // 添加购物车项
    handleAddCartItem(e) {
        const { originId } = this.data;
        const productInfo = e.detail ? e.detail : e;
        cartAddItem(productInfo, originId);
        this.handleRefreshCartData();
    },
    // 减少购物车项
    handleMinusCartItem(e) {
        const productInfo = e.detail ? e.detail : e;
        this._handleMinusCartItem(productInfo);
    },
    // 移除购物车项
    handleRemoveCartItem(e) {
        const { cartInfo } = this.data;
        const productInfo = e.detail ? e.detail : e;
        const count = cartInfo.map[productInfo.productId] ? cartInfo.map[productInfo.productId].count : 1;
        this._handleMinusCartItem(productInfo, count);
    },
    _handleMinusCartItem(productInfo, count = 1) {
        const { originId } = this.data;
        cartMinusItem(productInfo, originId, count);
        this.handleRefreshCartData();
    },
};

/**
 * 中奖记录(兑奖)相关
 */
export const RedeemPrizeToOrderReviewMixins = {
    // 兑奖下单
    async handleRedeemPrize(e) {
        const { activityInfo } = e.detail;
        const { activityId: originId, brandId } = activityInfo;
        const { isWxpayAvailable } = await getBrandConfig(brandId);
        activityInfo.isWxpayAvailable = isWxpayAvailable;
        clearCartData(originId);
        clearOrderOriginInfo(originId);
        this.setData({
            originId,
            originInfo: activityInfo,
            canModifySku: true,
        }, () => {
            this.handleAutoAddCart();
            this.handleShowProductList();
        });
    },
    handleToOrderDetail(e) {
        const { orderNumber } = e.detail;
        navTo(PACKAGE_ORDER_PAGE.orderDetail, {
            orderNumber,
        });
    },
};

/**
 * 微信支付提示
 */
export const WxpayApplymentTipMixins = {
    handleShowWxpayTip(params) {
        const { brandId, canManage = false, isWxpayAvailable = false } = params;
        if (!isWxpayAvailable) {
            if (canManage) {
                TipDialog({
                    title: '温馨提示',
                    message: '请尽快申请开通微信商户账号，否则用户无法参与，完成下单支付',
                    confirmButtonText: '立即开通',
                    ok() {
                        navTo(PACKAGE_STAR_PAGE['brandWxpayApplyment'], {
                            brandId
                        });
                    },
                });
            } else {
                TipDialog({
                    title: '温馨提示',
                    message: '商家未配置收款账号，无法下单',
                    confirmButtonText: '我知道了',
                    showCancelButton: false,
                });
            }
            return false;
        }
        return true;
    },
};

/**
 * 加粉管理列表 mixins
 */
export const SnsListMixins = {
    data: {
        addSnsActionSheet: {
            show: false,
            list: SNS_TYPE_MENU,
        },
        moreSnsActionSheet: {
            show: false,
            list: [
                { name: '编辑', value: 'edit' },
                { name: '删除', value: 'delete' }
            ]
        },
        selectSnsInfo: {},
    },
    handleShowAddSnsActionSheet() {
        this.setData({
            'addSnsActionSheet.show': true,
        });
    },
    handleCloseAddSnsActionSheet() {
        this.setData({
            'addSnsActionSheet.show': false,
        });
    },
    handleSelectAddSnsActionSheet(e) {
        const { value } = e.detail;
        const { manageTargetType } = this.data;
        if (manageTargetType === TARGET_TYPE.brand) {
            navTo(PACKAGE_STAR_PAGE['brandSnsEdit'], {
                type: value,
            });
        } else if (manageTargetType === TARGET_TYPE.brand) {
            navTo(PACKAGE_STORE_PAGE['storeSnsEdit'], {
                type: value,
            });
        }
        this.handleCloseAddSnsActionSheet();
    },
    handleShowMoreSnsActionSheet(e) {
        this.setData({
            'moreSnsActionSheet.show': true,
            selectSnsInfo: e.detail,
        });
    },
    handleCloseMoreSnsActionSheet() {
        this.setData({
            'moreSnsActionSheet.show': false,
        });
    },
    handleSelectMoreSnsActionSheet(e) {
        const { value } = e.detail;
        const { manageTargetType, selectSnsInfo } = this.data;
        const { type, snsId } = selectSnsInfo;
        if (manageTargetType === TARGET_TYPE.brand) {
            if (value === 'edit') {
                navTo(PACKAGE_STAR_PAGE['brandSnsEdit'], {
                    snsId,
                    type,
                });
            } else if (value === 'delete') {
    
            }
        } else if (manageTargetType === TARGET_TYPE.brand) {
            if (value === 'edit') {
                navTo(PACKAGE_STORE_PAGE['storeSnsEdit'], {
                    snsId,
                    type,
                });
            } else if (value === 'delete') {
    
            }
        }
        this.handleCloseMoreSnsActionSheet();
    },
};
